#coding:utf-8

import matplotlib.pyplot as plt
import numpy as np
from scipy.misc import imread,imresize



def conv_forward_native(x,w,b,conv_param):
    out=None
    stride = conv_param['stride']
    pad = conv_param['pad']
    N, C, W, H = x.shape
    F, C, WH, WW = w.shape
    H_out = 1 + int((H + 2 * pad - WH) / stride)
    W_out = 1 + int((W + 2 * pad - WW) / stride)
    npad = ((0, 0), (0, 0), (pad, pad), (pad, pad))
    # 数据填充，维度N是前后填充大小(0,0)，维度W是前后填充大小(pad,pad)
    # 同理C&H ,数值是使用常数0填充
    x_pad = np.pad(x, pad_width=npad, mode='constant', constant_values=0)
    out=np.zeros((N,F,H_out,W_out))

    for i in  range(N):
        for j in range(F):
            for k in range(H_out):
                for z in range(W_out):
                    out[i,j,k,z]=np.sum(x_pad[i,:,k*stride:k*stride+WH, z*stride:z*stride+WW]*w[j, :, :, :])+b[j]
    cache = (x, w, b, conv_param)
    return out, cache

def imshow_noax(img, normalize=True):
    """ Tiny helper to show images as uint8 and remove axis labels """
    if normalize:
        img_max, img_min = np.max(img), np.min(img)
        img = 255.0 * (img - img_min) / (img_max - img_min)
    plt.imshow(img.astype('uint8'))
    plt.gca().axis('off')


if __name__=="__main__":
    plt.rcParams['figure.figsize'] = (10.0, 8.0)  # set default size of plots
    plt.rcParams['image.interpolation'] = 'nearest'
    plt.rcParams['image.cmap'] = 'gray'

    tower=imread('../data/test.jpg')
    print(tower.shape)
    img_size=200
    x=np.zeros((1,3,img_size,img_size))
    x[0,:,:,:]=imresize(tower,size=(img_size,img_size)).transpose(2,0,1)

    #两个卷积核，每个卷积的为w*h*d
    weights=np.zeros((2,3,3,3))

    # 第一个卷积核将 图片转为灰度图
    # 分别设置RGB通道的值
    weights[0, 0, :, :] = [[0, 0, 0], [0, 0.3, 0], [0, 0, 0]]
    weights[0, 1, :, :] = [[0, 0, 0], [0, 0.6, 0], [0, 0, 0]]
    weights[0, 2, :, :] = [[0, 0, 0], [0, 0.1, 0], [0, 0, 0]]

    # 获取B通道的水平信息
    weights[1, 2, :, :] = [[1, 2, 1], [0, 0, 0], [-1, -2, -1]]

    #第一个卷积核不需要bias
    bias=np.array([0,128])

    out, _ = conv_forward_native(x, weights, bias, {'stride': 1, 'pad': 1})

    # Show the original images and the results of the conv operation
    plt.subplot(1, 3, 1)
    imshow_noax(tower, normalize=False)
    plt.title('Original image')
    plt.subplot(1, 3, 2)
    imshow_noax(out[0, 0])
    plt.title('Grayscale')
    plt.subplot(1, 3, 3)
    imshow_noax(out[0, 1])
    plt.title('Edges')
    plt.show()

    # plt.imshow(x[0].transpose(1,2,0))
    #
    # plt.show()
